import QtQuick
import QtQuick.Controls
import QtQuick.Layouts

ApplicationWindow {
    id: window
    width: 450
    height: 400
    visible: true
    title: "System Info"

    // 增加多种IP定位方法
    function fetchLocationByIP() {
        locationText.text = "正在获取位置信息..."
        // 尝试不同的服务
        var services = [
                    {name: "ip-api", url: "http://ip-api.com/json"},
                    {name: "geoip", url: "https://freegeoip.app/json/"}
                ]
        
        // 随机选择一个服务，避免总是使用同一个
        var service = services[Math.floor(Math.random() * services.length)]
        console.log("使用 " + service.name + " 获取位置")
        
        var request = new XMLHttpRequest()
        request.open("GET", service.url)
        
        request.onload = function() {
            if (request.status === 200) {
                try {
                    var json = JSON.parse(request.responseText)
                    var locationInfo = "位置信息 (基于IP，可能不准确):\n"

                    // 根据不同服务解析不同字段
                    if (service.name === "ipinfo") {
                        if (json.country) locationInfo += "国家: " + json.country + "\n"
                        if (json.region) locationInfo += "省份: " + json.region + "\n"
                        if (json.city) locationInfo += "城市: " + json.city + "\n"
                        if (json.postal) locationInfo += "邮编: " + json.postal + "\n"
                    }
                    else if (service.name === "ip-api") {
                        if (json.country) locationInfo += "国家: " + json.country + "\n"
                        if (json.regionName) locationInfo += "省份: " + json.regionName + "\n"
                        if (json.city) locationInfo += "城市: " + json.city + "\n"
                        if (json.district) locationInfo += "区县: " + json.district + "\n"
                        if (json.zip) locationInfo += "邮编: " + json.zip + "\n"
                    }
                    else if (service.name === "geoip") {
                        if (json.country_name) locationInfo += "国家: " + json.country_name + "\n"
                        if (json.region_name) locationInfo += "省份: " + json.region_name + "\n"
                        if (json.city) locationInfo += "城市: " + json.city + "\n"
                        if (json.zip_code) locationInfo += "邮编: " + json.zip_code + "\n"
                    }

                    // 添加坐标信息
                    var lat = service.name === "ipinfo" ? (json.loc ? json.loc.split(",")[0] : null) :
                                                          (service.name === "ip-api" ? json.lat : json.latitude)
                    var lon = service.name === "ipinfo" ? (json.loc ? json.loc.split(",")[1] : null) :
                                                          (service.name === "ip-api" ? json.lon : json.longitude)

                    if (lat && lon) {
                        locationInfo += "坐标: " + lat + ", " + lon + "\n"
                    }

                    // 添加ISP信息，可能有助于判断位置
                    if ((service.name === "ipinfo" && json.org) ||
                            (service.name === "ip-api" && json.isp) ||
                            (service.name === "geoip" && json.isp)) {
                        locationInfo += "ISP: " + (json.org || json.isp) + "\n"
                    }
                    locationText.text = locationInfo

                } catch (error) {
                    console.log("解析IP位置失败:", error)
                    locationText.text = "位置: 无法解析位置数据"
                }
            } else {
                console.log("获取位置失败，状态码:", request.status)
                // 尝试下一个服务
                if (services.indexOf(service) < services.length - 1) {
                    var nextIndex = (services.indexOf(service) + 1) % services.length
                    service = services[nextIndex]
                    request.open("GET", service.url)
                    request.send()
                } else {
                    locationText.text = "位置: 所有服务均不可用"
                }
            }
        }
        
        request.onerror = function() {
            console.log("位置请求网络错误")
            locationText.text = "位置: 网络请求失败"
        }
        
        request.timeout = 5000
        request.send()
    }
    
    // IP获取功能
    function fetchIP() {
        ipText.text = "正在获取IP..."
        var request = new XMLHttpRequest()
        var endpoints = [
                    "https://api.ipify.org?format=json",
                    "https://ipinfo.io/json",
                    "http://httpbin.org/ip"
                ]

        function tryNext() {
            if (endpoints.length === 0) {
                ipText.text = "IP: 所有服务不可用"
                return
            }

            var url = endpoints.shift()
            request.abort()
            request.open("GET", url)

            request.onload = function() {
                if (request.status === 200) {
                    try {
                        var json = JSON.parse(request.responseText)
                        var ip = json.ip || json.origin
                        ipText.text = ip ? "IP: " + ip : "IP: 获取成功但无IP"

                        // 获取IP后立即获取位置信息
                        fetchLocationByIP()
                    } catch (error) {
                        ipText.text = "IP: 解析响应失败"
                        tryNext()
                    }
                } else {
                    tryNext()
                }
            }

            request.onerror = tryNext
            request.ontimeout = tryNext
            request.timeout = 3000
            request.send()
        }

        tryNext()
    }
    
    // 定时器更新当前时间
    Timer {
        interval: 1000
        running: true
        repeat: true
        onTriggered: {
            timeText.text = "当前时间: " + Qt.formatDateTime(new Date(), "yyyy-MM-dd hh:mm:ss")
        }
    }
    
    // 启动时获取IP
    Component.onCompleted: {
        fetchIP()
    }
    
    ColumnLayout {
        anchors.fill: parent
        anchors.margins: 20
        spacing: 15
        
        Text {
            id: timeText
            font.pixelSize: 18
            Layout.alignment: Qt.AlignHCenter
            text: "正在获取时间..."
        }
        
        Text {
            id: ipText
            font.pixelSize: 18
            Layout.alignment: Qt.AlignHCenter
            text: "正在获取IP..."
        }
        
        Rectangle {
            Layout.fillWidth: true
            Layout.fillHeight: true
            border.width: 1
            border.color: "#cccccc"
            radius: 5
            
            ScrollView {
                anchors.fill: parent
                anchors.margins: 10
                clip: true
                
                Text {
                    id: locationText
                    font.pixelSize: 16
                    text: "正在获取位置信息..."
                    width: parent.width
                    wrapMode: Text.WordWrap
                }
            }
        }
        
        Button {
            text: "刷新位置信息"
            Layout.alignment: Qt.AlignHCenter
            onClicked: fetchLocationByIP()
        }
    }
}
